package com.dc.base.util.wechat;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.URL;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;

import com.alibaba.fastjson.JSONObject;

public class WechatUtil {
	public static final String appID = "wx99622557934b7594";
	public static final String appsecret = "2fd4301feafe0566ce1982614d212528";
	private static String access_token_base = "";
	private static long access_token_base_time = 0;//access_token有效时间
	private static String getOpenIdUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=appID_string&secret=appsecret_string&code=code_string&grant_type=authorization_code";
	private static String getAccessTokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=appID_string&secret=appsecret_string";
	private static String getUserInfoUrl = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=access_token_string&openid=openid_string";
	
	public static void main(String[] args) {
		System.out.println(getBaseAccessToken());
		System.out.println(access_token_base);
		System.out.println(access_token_base_time);
	}
	
	/**
	 * 根据回调的code值获取openId
	 * @Title: getOpenId 
	 * @param code
	 * @return: String
	 * @author: ShenHJ
	 * Date: 2018年4月10日 下午2:36:21
	 */
	public static String getOpenId(String code) {
		String getOpenIdUrl = WechatUtil.getOpenIdUrl.replace("appID_string", WechatUtil.appID)
				.replace("appsecret_string", WechatUtil.appsecret).replace("code_string", code);
		JSONObject jsonObject = JSONObject.parseObject(httpRequest(getOpenIdUrl, "POST", null));
		return jsonObject.getString("openid");
	}

	/**
	 * 获取基础的BaseAccessToken,并且缓存在静态字段中
	 * @Title: getAccessToken 
	 * @return: String
	 * @author: ShenHJ
	 * Date: 2018年4月10日 下午2:36:35
	 */
	public static String getBaseAccessToken() {
		long nowTime = System.currentTimeMillis();
		//当当前时间超过access_token的有限时间时或者access_token为空时重新获取
		if (nowTime - WechatUtil.access_token_base_time >= 0 || "".equals(WechatUtil.access_token_base)) {
			String getAccessTokenUrl = WechatUtil.getAccessTokenUrl.replace("appID_string", WechatUtil.appID)
					.replace("appsecret_string", WechatUtil.appsecret);
			JSONObject jsonObject = JSONObject.parseObject(httpRequest(getAccessTokenUrl, "POST", null));
			WechatUtil.access_token_base = jsonObject.getString("access_token");
			WechatUtil.access_token_base_time = nowTime + 5400000;//微信api说的是2小时，我设置为1小时半
		}
		return WechatUtil.access_token_base;
	}
	
	
	/**
	 * get或者post请求，其中GET和POST参数需要大写
	 * @Title: httpRequest 
	 * @param requestUrl
	 * @param requestMethod
	 * @param outputStr
	 * @return: String
	 * @author: ShenHJ
	 * Date: 2018年4月10日 下午2:36:55
	 */
	public static String httpRequest(String requestUrl, String requestMethod, String outputStr) {
		StringBuffer buffer = new StringBuffer();
		try {
			// 创建SSLContext对象，并使用我们指定的信任管理器初始化
			TrustManager[] tm = { new MyX509TrustManager() };
			SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
			sslContext.init(null, tm, new java.security.SecureRandom());
			// 从上述SSLContext对象中得到SSLSocketFactory对象
			SSLSocketFactory ssf = sslContext.getSocketFactory();
			URL url = new URL(requestUrl);
			HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();
			httpUrlConn.setSSLSocketFactory(ssf);
			httpUrlConn.setDoOutput(true);
			httpUrlConn.setDoInput(true);
			httpUrlConn.setUseCaches(false);
			// 设置请求方式（GET/POST）
			httpUrlConn.setRequestMethod(requestMethod);
			if ("GET".equalsIgnoreCase(requestMethod))
				httpUrlConn.connect();
			// 当有数据需要提交时
			if (null != outputStr) {
				OutputStream outputStream = httpUrlConn.getOutputStream();
				// 注意编码格式，防止中文乱码
				outputStream.write(outputStr.getBytes("UTF-8"));
				outputStream.close();
			}
			// 将返回的输入流转换成字符串
			InputStream inputStream = httpUrlConn.getInputStream();
			InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
			BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
			String str = null;
			while ((str = bufferedReader.readLine()) != null) {
				buffer.append(str);
			}
			bufferedReader.close();
			inputStreamReader.close();
			// 释放资源
			inputStream.close();
			inputStream = null;
			httpUrlConn.disconnect();
		} catch (ConnectException ce) {
			System.out.println("Weixin server connection timed out." + ce.getMessage());
		} catch (Exception e) {
			System.out.println("https request error:{}" + e.getMessage());
		}
		return buffer.toString();
	}
	 
}
